package com.liuwei.netty.packet;

import com.liuwei.netty.coder.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        // 创建一个线程组用于时间循环
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);
        // 创建客户端启动对象
        try {
            Bootstrap bootstrap = new Bootstrap();
            // 设置相关参数
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加处理器
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加处理器,分包编码器
                            pipeline.addLast(new MessageEncoder());
                            // 添加业务代码
                            pipeline.addLast(new NettyMessageClientHandler());
                        }
                    });
            log.info("Netty客户端启动了......");
            // 同步阻塞连接
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9090).sync();
            // 同步阻塞关闭连接
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
